#include <project.h>
#include "userMain.h"

typedef enum
{
    STATE_CAPSENSE = 0x00u,
    STATE_ADC      = 0x01u
}SCAN_MODE;

/* Variable to store the next state */
extern SCAN_MODE scanState;//SCAN_MODE scanState = STATE_CAPSENSE;
extern uint8 adc_cnt;   
//extern uint8 mVolts1,mVolts2;

//#define BUTTON_NUM	8
#define NODE_TYPE   0x03
unsigned char cNodeValue	   = 0;
unsigned char cCount		   = 0;

unsigned int lKeyChecked       = 0;

unsigned int lTimer            = 0;
//unsigned int lRelayTimer       = 0;
//unsigned int LedTimer          = 0;
unsigned int lKeyTimer         = 0;
//unsigned int lEngerTimer       = 0;
//unsigned int NightTimer        = 0;
unsigned int CSD_RestTimer     = 0;     
//unsigned int FirstUploadTimer = 0;
unsigned int Send_dateTimer    = 0;
//unsigned int Zero_dateTimer    = 0;
//unsigned int ZeroTimer         = 0;

//unsigned char Relayflag        = 0;
//unsigned char ZeroFlag         = 0;
//unsigned char OldZeroFlag      = 0;
//unsigned char bflag            = 0;
//unsigned char uartflag         = 0;
//unsigned char OneZeroFlag      = 0;


//unsigned char sKeyID           = 0;
//unsigned char BlinkValue       = 0;
//unsigned char olddevId         = 0;
//unsigned char RecviceDataTimes = 0xff;
//unsigned char RecviceDataType  = 0xff;
//unsigned char LedNodestatus    = 0;     
//unsigned char ReciveMoveBits   = 0; 
unsigned char TouchFlag        = 0;
//unsigned char TouchPanel       = 0;
unsigned char pressLong        = 0;
//unsigned char MessageID        = 0;
unsigned char KeyID            = 0;
unsigned char BacklightLux     = 10;
//unsigned char NodeTypeCount = NODE_TYPE;    
//unsigned int  NodeTypeTime     = 0;           

uint8 LedFlashStauts           = 0;

unsigned char  Keyvalue        = 0;
unsigned char  OldKeyvalue     = 0;   
unsigned char  CountNum        = 0;  
//unsigned char  buff[8]         = {0};
//unsigned char  Slbuffer[8]     = {0};
//unsigned char  BackupData[10]  = {0};
unsigned char  userKeyValue = 0;


unsigned int timer_sub(unsigned int lStartTimer) //定时时间设置
{
	if(!lStartTimer)
		return 0;
	if(lTimer >= lStartTimer)
		return lTimer - lStartTimer;
	return 0xffff - lStartTimer + lTimer;
}

unsigned int start_timer(void)//使能定时器
{
	return lTimer?lTimer:1;
}

unsigned char even_parity(unsigned char value,unsigned char n_bits)//掌拍校验
{
   unsigned char parity = 0;	 
	 while(n_bits>0)
	 {
       //******************************
	   if(n_bits !=4 )
       {
            parity += value&0x01;
       }//********************************/
       //parity += value&0x01; 
	   value >>= 1;
	   n_bits -= 1;
	 }
	 return parity;
}

void userKeypadScanInitFunc(void)
{
    /* Start CapSense_ADC component */
    CapSense_Start();
    /* Scan the CapSense sensor */
    CapSense_ScanAllWidgets();
}

unsigned char user_cnt=0;
unsigned char userKeypadScanFunc(void)
{
    unsigned int lKeyStatue;	
    unsigned char KeyActive = 0; 	
    //CapSense_ADC_UpdateEnabledBaselines(); 
    KeyActive = CapSense_IsAnyWidgetActive();
	if(KeyActive)
	{		   
		user_cnt++;
        if(CapSense_dsRam.snsStatus[0])
		{ 			
		   Keyvalue |= 0x01;//0x80;  //10
		}
		if(CapSense_dsRam.snsStatus[1])
		{            
			Keyvalue |= 0x02;//0x40;    //20 
		}
		if(CapSense_dsRam.snsStatus[2])
		{
			Keyvalue |= 0x04;//0x20;    //40
		}			
		if(CapSense_dsRam.snsStatus[3])
		{            
			Keyvalue |= 0x08;//0x10;    //80
		}
		if(CapSense_dsRam.snsStatus[4])
		{             
			Keyvalue |= 0x10;//0x01;    //01
		}
		if(CapSense_dsRam.snsStatus[5])
		{            
			Keyvalue |= 0x20;//0x02;    //02
		}
		if(CapSense_dsRam.snsStatus[6])
		{             
			Keyvalue |= 0x40;//0x04;    //04
		}
		//if(CapSense_dsRam.snsStatus[7])
		//{            
		//	Keyvalue |= 0x08;    //08
		//}
        
		if(OldKeyvalue != Keyvalue)//判断是否有键按下
		{
			OldKeyvalue = Keyvalue;								
			lKeyTimer	= 0;
			CountNum++;			
			return 1;        //返回值为1
		}              
	}
    else	
	{		
		Keyvalue      = 0;	
        if(user_cnt) 
            user_cnt = 0;
	}	
	lKeyStatue = (unsigned int)Keyvalue;	
	if(lKeyStatue)
	{      
	    if(lKeyChecked != 0xffff)
		{    
			if(lKeyChecked != lKeyStatue)
			{
				lKeyTimer	= start_timer();  
				lKeyChecked	= lKeyStatue;				
			}
			else
			{   
               	if( timer_sub(lKeyTimer)>= 3000) 
        		{					
        			lKeyTimer	  = 0;  
        		    CountNum      = 0;         //++wangsm20130412					
        			lKeyChecked   = lKeyStatue;     
                    CSD_RestTimer = start_timer(); 
        		}                 
			}
		}			
	}
	else
	{	
		if(timer_sub(lKeyTimer) > 100)     //300		
		{		 	 
		   lKeyTimer	= 0;	
		}    
		else
			lKeyChecked	= 0;
		CountNum     = 0;
        CSD_RestTimer = 0;        
	}
	
	if((!lKeyTimer)&&(lKeyChecked)&&(lKeyChecked != 0xffff))
    {         
	   if(lKeyChecked & 0x00ff)
	   {  	     
	      cCount = (unsigned char)(lKeyChecked& 0x00ff);	//提取低8位，	          
          pressLong	= (0 != lKeyStatue);  
          if((cCount&0xff)>=1)//判断触摸是否有效 1217
            TouchFlag=1;
		  if(lKeyStatue)
			{            
               if(cCount==0x01)
                       KeyID =0x01;
               else if(cCount==0x02)
                       KeyID =0x02;
               else if(cCount==0x04)
                       KeyID =0x03;
               else if(cCount==0x08)
                       KeyID =0x04;
               else if(cCount==0x10)
                       KeyID =0x05;
               else if(cCount==0x20)
                       KeyID =0x06;
               else if(cCount==0x40)
                       KeyID =0x07;
               else if(cCount==0x11)
                       KeyID =0x15;         //Local 1 + Func 1
               else if(cCount==0x03)
                       KeyID =0x12;         //Local 1 + Local 2
              else if(cCount==0x05)
                       KeyID =0x13;         //Local 1 + Local 3
             else if(cCount==0x09)
                       KeyID =0x14;         //Local 1 + Local 4
             else if(cCount==0x06)
                       KeyID =0x22;         //Local 2 + Local 3
               else
               	       return 0;
                Send_dateTimer = start_timer(); 		
			}
		  else
			{ 
			  unsigned char i;
              unsigned char m_bits;
              m_bits = even_parity(cCount,8);//判断是否单按还是掌拍 1220
			  if(m_bits>=3)    // 
				{		
                    
						if(NODE_TYPE ==0x01)					
						{
						   cCount = 0x01; 
						}
						else if(NODE_TYPE ==0x02) 
						{ 
						   cCount = 0x03;  
						}
						else if(NODE_TYPE ==0x03)
						{ 
						   cCount = 0x07;  
						}
						else if(NODE_TYPE ==0x04)
						{ 
						   cCount = 0x0f; 
						}
					    KeyID = 0x0C;
					  lKeyChecked	  = 0xffff;
				    return 0;				  	
				}
				for(i=0;i<8;i++)//检测哪个按键被按
				{
					if(cCount & (0x01 << i))
					{
						cCount = 0x01 << i;
						break;            
					} 
				}
                if(cCount!=0)//按键ID_L
                { 
		         if(cCount==0x01)
		                 KeyID=0x01;
		         else if(cCount==0x02)
		                 KeyID=0x02;
		         else if(cCount==0x04)
		                 KeyID=0x03;
		         else if(cCount==0x08)
		                 KeyID=0x04;
                 else if(cCount==0x10)
		                 KeyID=0x05;
		         else if(cCount==0x20)
		                 KeyID=0x06;
		         else if(cCount==0x40)
		                 KeyID=0x07;
		         else 
                        return 0;
                 }        
                Send_dateTimer = start_timer();            //发送数据定时器启动
			}	   
	   }	
	   lKeyChecked	= 0xffff;		
	}
	return 0;
}
void userKeyScanTimerTick(void)
{
    lTimer++; 
}

void userGetKeyValueFunc(void)
{
    userKeyValue = KeyID;
    if(userKeyValue==0) return ;
    if(pressLong)
    {
        userKeyValue |= 0x80;
    }
    KeyID = 0;
    _NOP;
    userKeyProcess();
}

void userCapsenseAdcFunc(void)
{
    if( (CapSense_NOT_BUSY == CapSense_IsBusy())&& (CapSense_AdcSTATUS_IDLE == CapSense_AdcIsBusy()) )
    {
        /* If scan state is CapSense, initiate CapSense scan and 
               process last cycle ADC data 
        */
        if(scanState == STATE_CAPSENSE)
        {
            /* Scan configured sensor */
            CapSense_ScanAllWidgets();
             
            /* Read the measured voltage value from last ADC cycle */
            if(adc_cnt == 0)
            {
                //mVolts1 = CapSense_AdcReadResult_mVolts(CapSense_AdcCHANNEL_0);
                userMotionSensorAdcSampleFunc();
            }
            if(adc_cnt == 1)
            {
                //mVolts2 = CapSense_AdcReadResult_mVolts(CapSense_AdcCHANNEL_1);
                userLightSensorAdcSampleFunc();
            }
            /* Configure next scan state to ADC to perform input voltage measurement */
            scanState = STATE_ADC;
        }
        else if (scanState == STATE_ADC)
        {
            adc_cnt++;
            if(adc_cnt == 2)
            {   
                adc_cnt = 0;
            }
            /* Start an ADC Conversion conversion */
            if(adc_cnt == 0)
                CapSense_AdcStartConvert(CapSense_AdcCHANNEL_0);
            if(adc_cnt == 1) 
                CapSense_AdcStartConvert(CapSense_AdcCHANNEL_1);
                
            /* Process previous cycle CapSense Data */
            CapSense_ProcessAllWidgets();
            userKeypadScanFunc();
            //Capsense_pross();
                
            /* Set variable to scan CapSense sensor in the next cycle */
            scanState = STATE_CAPSENSE;
        }
    }
    else
    {
        if(timer_sub(CSD_RestTimer)>20000)   //20S后复位触摸模块
        {
           CSD_RestTimer = 0; 
           CapSense_InitializeAllBaselines(); 
        }       
    }
}



